<template>
  <div class="app-container">
    <search-table-pagination :loading="loading" :data="list" :columns="columns" :form-options="formOptions" :url="api.admin_admin" method="get" type="local">
      <el-button
        slot="btn"
        type="danger"
        plain
        icon="el-icon-plus"
        @click="handleCreate()"
      >
        {{ $t('btn.create') }}
      </el-button>
      <template slot="append">
        <el-table-column
          :label="$t('table.changePassword')"
          fixed="right"
          align="center"
          width="150">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="small"
              @click.native.prevent="handlePassword(scope.row)">
              {{ $t('table.changePassword') }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('table.operate')"
          align="center"
          fixed="right"
          width="200">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="small"
              @click.native.prevent="handleEdit(scope.row)">
              {{ $t('btn.edit') }}
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click.native.prevent="handleDel(scope.row, scope.$index)">
              {{ $t('btn.delete') }}
            </el-button>
          </template>
        </el-table-column>
      </template>
    </search-table-pagination>
    <!-- 操作 -->
    <el-dialog :title="isCreate ? $t('tips.add'): $t('table.edit')" :visible.sync="dialogFormVisible" :before-close="closeDialog">
      <el-form ref="dataForm" :model="formData" :rules="rules" label-position="left" label-width="160px" style="width: 400px; margin-left:50px;">
        <el-tabs v-model="activeName" type="card">
          <el-tab-pane :label="$t('table.basicInformation')" name="first">
            <el-form-item :label="$t('table.roleName')" prop="role_id">
              <el-select v-model="formData.role_id" placeholder="请选择" @change="changeRole">
                <el-option
                  v-for="item in roleList"
                  :key="item.id"
                  :label="item.rolename"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('table.username')" prop="username">
              <el-input v-model="formData.username"/>
            </el-form-item>
            <el-form-item v-if="isCreate" :label="$t('table.password')" prop="password">
              <el-input v-model="formData.password"/>
            </el-form-item>
            <el-form-item :label="$t('table.email')" prop="email">
              <el-input v-model="formData.email"/>
            </el-form-item>
            <el-form-item :label="$t('table.mobile')" prop="mobile">
              <el-input v-model="formData.mobile"/>
            </el-form-item>
            <el-form-item :label="$t('table.status')" prop="status">
              <el-radio v-model="formData.status" :label="1">{{ $t('btn.yes') }}</el-radio>
              <el-radio v-model="formData.status" :label="0">{{ $t('btn.no') }}</el-radio>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane :label="$t('table.authorityAllocation')" name="second">
            <el-form-item class="permission" prop="permission">
              <el-tree
                ref="tree"
                :data="permissionList"
                :props="defaultProps"
                show-checkbox
                default-expand-all
                node-key="name"
                highlight-current/>
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">{{ $t('btn.cancel') }}</el-button>
        <el-button v-if="isCreate" type="primary" @click="createData">{{ $t('btn.confirm') }}</el-button>
        <el-button v-else type="primary" @click="updateData">{{ $t('btn.confirm') }}</el-button>
      </div>
    </el-dialog>
    <!-- 修改密码 -->
    <el-dialog :title="$t('table.changePassword')" :visible.sync="dialogChangePassword" :before-close="closeDialogPassword">
      <el-form ref="changePasswrodForm" :model="passwordData" :rules="rulePassword" label-width="160px" style="width: 70%; margin-left:50px;">
        <el-form-item :label="$t('table.newPassword')" prop="password">
          <el-input v-model="passwordData.password"/>
        </el-form-item>
        <el-form-item :label="$t('table.confirmPassword')" prop="repassword">
          <el-input v-model="passwordData.repassword"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialogPassword">{{ $t('btn.cancel') }}</el-button>
        <el-button type="primary" @click="confirmPassword">{{ $t('btn.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Http from '@/utils/http'
import { getRSApassword } from '@/utils/auth'
import { statusSelect } from '@/utils/data'
import { cache } from '@/utils/index'

export default {
  name: '',
  data() {
    const dialogData = {
      role_id: undefined,
      rolename: undefined,
      user_id: undefined,
      info: undefined,
      status: 1,
      permission: '[]',
      rsa_encrypt: 1
    }
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.$t('rules.password')))
      } else {
        if (this.passwordData.repassword !== '') {
          this.$refs.changePasswrodForm.validateField('repassword')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.$t('table.confirmPassword')))
      } else if (value !== this.passwordData.password) {
        callback(new Error(this.$t('tips.passwordNoMatch')))
      } else {
        callback()
      }
    }
    return {
      statusSelect,
      roleList: [],
      list: {},
      loading: false,
      dialogFormVisible: false,
      dialogChangePassword: false,
      isCreate: false,
      rules: undefined,
      activeName: 'first',
      columnData: {},
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      passwordData: {
        password: '',
        repassword: ''
      },
      formData: dialogData,
      resetData: dialogData,
      permissionList: [],
      rulePassword: {
        password: [
          { validator: validatePass, trigger: 'blur' }
        ],
        repassword: [
          { validator: validatePass2, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    formOptions() {
      return {
        showResetBtn: true,
        forms: [
          { prop: 'mobile', md: 12, label: 'table.mobile' },
          { prop: 'username', md: 12, label: 'table.username' },
          { prop: 'status', md: 12, label: 'table.status', itemType: 'select', options: statusSelect },
          { prop: 'role_id', md: 12, label: 'table.roleName', itemType: 'select', options: [] }
        ]
      }
    },
    columns() {
      return [
        { prop: 'id', minWidth: 80, label: this.$t('table.id') },
        { prop: 'username', minWidth: 150, label: this.$t('table.username') },
        { prop: 'mobile', minWidth: 150, label: this.$t('table.mobile') },
        { prop: 'email', minWidth: 150, label: this.$t('table.email') },
        { prop: 'login_count', label: this.$t('table.loginCount') },
        { prop: 'status', minWidth: 80, label: this.$t('table.status'), filter: 'statusFmt' },
        { prop: 'last_login_ip', minWidth: 150, label: this.$t('table.lastLoginIp') },
        { prop: 'last_login_at', minWidth: 150, label: this.$t('table.lastLoginAt'), filter: 'parseTime|{y}-{m}-{d} {h}:{i}:{s},--'}
      ]
    }
  },
  mounted() {
    this.setRules()
    this.setRole()
    this.getPermission()
  },
  methods: {
    changeRole(id) {
      this.$refs.tree.setCheckedKeys([])
      const res = this.roleList.filter(v => v.id === id)
      this.$nextTick(() => {
        res[0].permission.forEach(v => {
          this.$refs.tree.setChecked(v, true, false)
        })
      })
    },
    setRules() {
      this.rules = {
        role_id: [{ required: true, message: this.$t('rules.role_id') }],
        username: [{ required: true, message: this.$t('rules.username') }],
        password: [{ required: true, message: this.$t('rules.password') }],
        email: [{ required: true, message: this.$t('rules.email') }],
        mobile: [{ required: true, message: this.$t('rules.mobile') }]
      }
    },
    async setRole() {
      const res = await Http.get(this.api.admin_valid_role)
      this.roleList = res.data
      this.formOptions.forms[3].options = res.data.map(v => {
        return {
          value: v.id,
          label: v.rolename
        }
      })
    },
    async fetchData() {
      this.loading = true
      const res = await Http.get(this.api.admin_admin)
      this.list = res
      this.loading = false
    },
    async getPermission() {
      const res = await Http.get(this.api.admin_menu)
      this.permissionList = res.data
    },
    async handleEdit(row) {
      this.formData = Object.assign({}, row)
      this.dialogFormVisible = true
      // this.$refs.tree.setCheckedNodes(row.permission || [])
      this.$nextTick(() => {
        row.permission.forEach(v => {
          this.$refs.tree.setChecked(v, true, false)
        })
      })
      // for (var j = 0; j < row.permission.length; j++) {
      //   this.$set(this.choosedRole, j, row.permission[j])
      // }
    },
    handlePassword(row) {
      this.formData = Object.assign({}, row)
      this.dialogChangePassword = true
    },
    confirmPassword() {
      this.$refs['changePasswrodForm'].validate((valid) => {
        if (valid) {
          const sys_cfg = cache('sys_cfg')
          var pwd = this.passwordData.password.trim()
          if (parseInt(sys_cfg.rsa_encrypt) === 1) {
            pwd = getRSApassword(sys_cfg.public_key, pwd)
          }
          var params = Object.assign({}, { password: pwd, admin_id: this.formData.id, rsa_encrypt: sys_cfg.rsa_encrypt })
          var url = this.api.admin_change_pwd
          Http.put(url, params).then(res => {
            this.$notify({
              title: this.$t('tips.success'),
              message: '修改密码' + this.$t('tips.success'),
              type: 'success',
              duration: 2000
            })
          })
          this.closeDialogPassword()
        } else {
          return false
        }
      })
    },
    async handleCreate() {
      this.isCreate = true
      // this.formData = {}
      this.dialogFormVisible = true
    },
    handleDel(row, i) {
      this.$confirm(this.$t('tips.deleteConfirm'))
        .then(_ => {
          var url = this.api.admin_admin + '/' + row.id
          this.submitData(url, 'delete', this.$t('tips.delete'), {}, i)
        })
        .catch(_ => _)
    },
    closeDialog() {
      this.formData = Object.assign({}, this.resetData)
      this.$refs.tree.setCheckedKeys([])
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      this.dialogFormVisible = false
      this.isCreate = false
    },
    closeDialogPassword() {
      this.$refs['changePasswrodForm'].clearValidate()
      this.$refs['changePasswrodForm'].resetFields()
      this.dialogChangePassword = false
    },
    updateData() {
      // const permission = JSON.stringify(this.$refs.tree.getCheckedNodes().map(v => v.code))
      let permission = JSON.stringify(this.$refs.tree.getCheckedNodes(false, true).map(v => v.name))
      if (permission === '[]') {
        permission = ''
      }
      var params = Object.assign({}, this.formData, { permission: permission, user_id: this.formData.id })
      var url = this.api.admin_admin + '/' + this.formData.id
      this.submitData(url, 'put', this.$t('tips.update'), params)
    },
    createData() {
      const permission = JSON.stringify(this.$refs.tree.getCheckedNodes().map(v => v.name))
      const pub_key = cache('pub_key')
      const RSA_PASSWORD = getRSApassword(pub_key, this.formData.password)
      var params = Object.assign({}, this.formData, { permission: permission }, { password: RSA_PASSWORD })
      var url = this.api.admin_admin
      this.submitData(url, 'post', this.$t('tips.add'), params)
    },
    submitData(url, method, msg, param, i) {
      this.submitDataBefore(method !== 'delete', _ => {
        Http.request(url, method, param || this.formData).then(res => {
          this.$notify({
            title: this.$t('tips.success'),
            message: msg + ' ' + this.$t('tips.success'),
            type: 'success',
            duration: 2000
          })
          this.fetchData()
        })
        i ? '' : this.closeDialog()
      })
    },
    submitDataBefore(isCheck, cb) {
      isCheck ? this.$refs.dataForm.validate(_ => _ && cb()) : cb()
    }
  }
}
</script>
<style lang="scss">
.permission{
  .el-form-item__content{
    margin-left: 0 !important;
  }
}
</style>

